package com.light.mytext.kedavoicetotext2;

import android.util.Base64;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.light.mytext.kedavoicetotext.DraftWithOrigin;
import com.light.mytext.kedavoicetotext.RTASRTest;
import com.light.mytext.model.PayEven;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.CountDownLatch;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import okhttp3.HttpUrl;

public class WebSockConnect {
    private static final String hostUrl = "https://iat-api.xfyun.cn/v2/iat"; //中英文，http url 不支持解析 ws/wss schema
    // private static final String hostUrl = "https://iat-niche-api.xfyun.cn/v2/iat";//小语种
    private static final String appid = "5fa8e182"; //在控制台-我的应用获取
    private static final String apiSecret = "34d7fe6b5f1e6d7791dbabfc594f1585"; //在控制台-我的应用-语音听写（流式版）获取
    private static final String apiKey = "18d5c07002252fb750c83ca57ae8d23f"; //在控制台-我的应用-语音听写（流式版）获取
    //    private static final String file = "resource\\iat\\16k_10.pcm"; // 中文
    private static final String file = "/storage/emulated/0/Android/data/com.tencent.mobileqq/Tencent/QQfile_recv/16k_10.pcm";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
    public static final int StatusFirstFrame = 0;
    public static final int StatusContinueFrame = 1;
    public static final int StatusLastFrame = 2;
    private static MyWebSocketClient client;
    public static final Gson json = new Gson();
    static Decoder decoder = new Decoder();
    // 开始时间
    private static Date dateBegin = new Date();
    // 结束时间
    private static Date dateEnd = new Date();

    public static void mainA() {
        // 构建鉴权url
        try {
            String urla = getAuthUrl(hostUrl, apiKey, apiSecret).replace("http://", "ws://").replace("https://", "wss://");
            URI url = new URI(urla);
            CountDownLatch handshakeSuccess = new CountDownLatch(1);
            CountDownLatch connectClose = new CountDownLatch(1);
            client = new MyWebSocketClient(url, handshakeSuccess, connectClose);

            client.connect();
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                System.out.println(getCurrentTimeStr() + "\t连接中");
                Thread.sleep(1000);
            }

            // 等待握手成功
            handshakeSuccess.await();
            System.out.println(sdf.format(new Date()) + " 开始发送音频数据");
            Log.i("RTASRTest", sdf.format(new Date()) + " 开始发送音频数据");

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static class MyWebSocketClient extends WebSocketClient {

        private CountDownLatch handshakeSuccess;
        private CountDownLatch connectClose;

        public MyWebSocketClient(URI serverUri, CountDownLatch handshakeSuccess, CountDownLatch connectClose) {
            super(serverUri);
            this.handshakeSuccess = handshakeSuccess;
            this.connectClose = connectClose;
        }

        @Override
        public void onOpen(ServerHandshake handshake) {
            System.out.println(getCurrentTimeStr() + "\t连接建立成功！");
            Log.i("RTASRTest", getCurrentTimeStr() + "\t连接建立成功！");
        }

        @Override
        public void onMessage(String text) {
            Log.i("RTASRTest", getCurrentTimeStr() + "\tonMessage！");
        }

        @Override
        public void onError(Exception e) {
            System.out.println(getCurrentTimeStr() + "\t连接发生错误：" + e.getMessage() + ", " + new Date());
            e.printStackTrace();
            System.exit(0);
        }

        @Override
        public void onClose(int arg0, String arg1, boolean arg2) {
            System.out.println(getCurrentTimeStr() + "\t链接关闭");
            connectClose.countDown();
        }

        @Override
        public void onMessage(ByteBuffer bytes) {
            try {
                System.out.println(getCurrentTimeStr() + "\t服务端返回：" + new String(bytes.array(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getCurrentTimeStr() {
        return sdf.format(new Date());
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        StringBuilder builder = new StringBuilder("host: ").append(url.getHost()).append("\n").//
                append("date: ").append(date).append("\n").//
                append("GET ").append(url.getPath()).append(" HTTP/1.1");
        //System.out.println(builder);
        Charset charset = Charset.forName("UTF-8");
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(builder.toString().getBytes(charset));
//        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String sha = Base64.encodeToString(hexDigits, Base64.NO_WRAP);

        //System.out.println(sha);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        //System.out.println(authorization);
        HttpUrl httpUrl = HttpUrl.parse("https://" + url.getHost() + url.getPath()).newBuilder().//
                addQueryParameter("authorization", Base64.encodeToString(authorization.getBytes(charset), Base64.NO_WRAP)).
//                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(charset))).//
        addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();
        return httpUrl.toString();
    }

    //解析返回数据，仅供参考
    public static class Decoder {
        private WebIATWS.Text[] texts;
        private int defc = 10;

        public Decoder() {
            this.texts = new WebIATWS.Text[this.defc];
        }

        public synchronized void decode(WebIATWS.Text text) {
            if (text.sn >= this.defc) {
                this.resize();
            }
            if ("rpl".equals(text.pgs)) {
                for (int i = text.rg[0]; i <= text.rg[1]; i++) {
                    this.texts[i].deleted = true;
                }
            }
            this.texts[text.sn] = text;
        }

        public String toString() {
            StringBuilder sb = new StringBuilder();
            for (WebIATWS.Text t : this.texts) {
                if (t != null && !t.deleted) {
                    sb.append(t.text);
                }
            }
            return sb.toString();
        }

        public void resize() {
            int oc = this.defc;
            this.defc <<= 1;
            WebIATWS.Text[] old = this.texts;
            this.texts = new WebIATWS.Text[this.defc];
            for (int i = 0; i < oc; i++) {
                this.texts[i] = old[i];
            }
        }

        public void discard() {
            for (int i = 0; i < this.texts.length; i++) {
                this.texts[i] = null;
            }
        }
    }
}
